package com.ruoyi.web.controller.system;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.Apptype;
import com.ruoyi.system.service.IApptypeService;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Appmanager;
import com.ruoyi.system.service.IAppmanagerService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 项目信息Controller
 * 
 * @author yaozh
 * @date 2024-01-09
 */
@RestController
@RequestMapping("/system/appmanager")
public class AppmanagerController extends BaseController
{
    @Resource
    private IAppmanagerService appmanagerService;

    @Resource
    private IApptypeService apptypeService;
    @Resource
    private TokenService tokenService;

    @Resource
    private ISysDeptService deptService;

    /**
     * 查询项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:list')")
    @GetMapping("/list")
    public TableDataInfo list(HttpServletRequest request, HttpServletResponse response, Appmanager appmanager)
    {
        startPage();
        List<Appmanager> list = appmanagerService.selectAppmanagerList(appmanager);
        return getDataTable(list);
    }

    /**
     * 导出项目信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:export')")
    @Log(title = "项目信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Appmanager appmanager)
    {
        List<Appmanager> list = appmanagerService.selectAppmanagerList(appmanager);
        ExcelUtil<Appmanager> util = new ExcelUtil<Appmanager>(Appmanager.class);
        util.exportExcel(response, list, "项目信息数据");
    }

    /**
     * 获取项目信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:query')")
    @GetMapping(value = "/{appid}")
    public AjaxResult getInfo(@PathVariable("appid") Long appid)
    {
        return success(appmanagerService.selectAppmanagerByAppid(appid));
    }

    /**
     * 新增项目信息
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:add')")
    @Log(title = "项目信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Appmanager appmanager)
    {
        if (!appmanagerService.checkAppExplainUnique(appmanager))
        {
            return error("新增项目'" + appmanager.getAppexplain() + "'失败，项目名称已存在");
        }
        if (!appmanagerService.checkAppNameUnique(appmanager))
        {
            return error("新增项目'" + appmanager.getAppexplain() + "'失败，数据库名称'" + appmanager.getAppName() + "'已存在");
        }
        return toAjax(appmanagerService.insertAppmanager(appmanager));
    }

    /**
     * 修改项目信息
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:edit')")
    @Log(title = "项目信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Appmanager appmanager)
    {
        Long appId = appmanager.getAppid();
        if (!appmanagerService.checkAppExplainUnique(appmanager))
        {
            return error("修改项目'" + appmanager.getAppexplain() + "'失败，项目名称已存在");
        }
        if (!appmanagerService.checkAppNameUnique(appmanager))
        {
            return error("修改项目'" + appmanager.getAppexplain() + "'失败，数据库名称'" + appmanager.getAppName() + "'已存在");
        }
        return toAjax(appmanagerService.updateAppmanager(appmanager));
    }

    /**
     * 删除项目信息，实际上只是更新项目的状态，没有真正删除数据
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:remove')")
    @Log(title = "项目信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{appids}")
    public AjaxResult remove(@PathVariable Long[] appids,String dbName)
    {
        LoginUser loginUser = getLoginUser();
        boolean isAdmin = loginUser.getUser().isAdmin();
        if(!isAdmin){
            String message = "拒绝操作，仅超级管理员权限才能删除！";
            throw new RuntimeException(message);
        }
        boolean canRemove = true;
        if(StringUtils.hasLength(dbName)){
            for(Long appid : appids){
                if(appid != null && dbName.startsWith(String.valueOf(appid))){
                    canRemove = false;
                    break;
                }
            }
        }
        if(!canRemove){
            String message = "删除项目失败，当前项目'" + dbName + "'正在使用，请切换到其它项目再删除该项目";
            throw new RuntimeException(message);
        }
        String state = "1";//项目是否放入回收站/数据状态（0正常/未放入回收站，就是未删除，1删除/放入回收站），0正常，1删除
        String runStatus = "0";//runStatus运行状态,0已停止,1运行中
        return toAjax(appmanagerService.updateAppManagerStatusByAppIds(appids,state,runStatus));
    }

    @PreAuthorize("@ss.hasPermi('system:appmanager:edit')")
    @Log(title = "恢复项目", businessType = BusinessType.UPDATE)
    @PutMapping("/restored/{appid}")
    public AjaxResult restored(@PathVariable Long appid)
    {
        String state = "0";//项目是否放入回收站/数据状态（0正常/未放入回收站，就是未删除，1删除/放入回收站），0正常，1删除
        String runStatus = "1";//runStatus运行状态,0已停止,1运行中
        return toAjax(appmanagerService.updateAppManagerStatusByAppId(appid,state,runStatus));
    }

    @PreAuthorize("@ss.hasPermi('system:appmanager:add')")
    @Log(title = "初始化项目信息", businessType = BusinessType.OTHER)
    @GetMapping("/init/{appid}")
    public AjaxResult init(@PathVariable Long appid)
    {

        Appmanager appmanager = appmanagerService.selectAppmanagerByAppid(appid);
        if (appmanager == null)
        {
            return error("初始化编号为'" + appid + "'的项目失败，项目不存在");
        }
        if ("1".equals(appmanager.getAppstate()))
        {
            return error("初始化项目'" + appmanager.getAppexplain() + "'失败，项目已经初始化");
        }
        String appName = appmanager.getAppName();
        if(!StringUtils.hasLength(appName)){
            return error("初始化项目'" + appmanager.getAppexplain() + "'失败，数据库名称为空");
        }
        String dbName = appmanager.getAppid() + appmanager.getAppName();
        int count = appmanagerService.checkDataBaseUnique(dbName);
        if(count > 0){
            return error("初始化项目'" + appmanager.getAppexplain() + "'失败，项目已经初始化");
        }
        return toAjax(appmanagerService.initAppManager(appmanager));
    }

    @PreAuthorize("@ss.hasPermi('system:appmanager:query')")
    @Log(title = "进入项目信息", businessType = BusinessType.OTHER)
    @GetMapping("/fix/{appid}")
    public AjaxResult fix(HttpServletRequest request,@PathVariable Long appid)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        Appmanager appmanager = appmanagerService.selectAppmanagerByAppid(appid);
        if (appmanager == null)
        {
            String message = "进入编号为'" + appid + "'的项目失败，项目不存在";
            record(loginUser,Constants.LOGIN_FAIL,message);
            return error("进入编号为'" + appid + "'的项目失败，项目不存在");
        }
        String appName = appmanager.getAppName();
        if(!StringUtils.hasLength(appName)){
            String message = "进入项目'" + appmanager.getAppexplain() + "'失败，数据库名称为空";
            record(loginUser,Constants.LOGIN_FAIL,message);
            return error("进入项目'" + appmanager.getAppexplain() + "'失败，数据库名称为空");
        }
        String dbName = appmanager.getAppid() + appmanager.getAppName();
        int count = appmanagerService.checkDataBaseUnique(dbName);
        if(count <= 0){
            String message = "进入项目'" + appmanager.getAppexplain() + "'失败，项目未初始化";
            record(loginUser,Constants.LOGIN_FAIL,message);
            return error("进入项目'" + appmanager.getAppexplain() + "'失败，项目未初始化");
        }
        String message = "进入项目：" + appmanager.getAppexplain();
        record(loginUser,Constants.LOGIN_SUCCESS,message);
        return success(dbName);
    }

    private void record(LoginUser loginUser,String status,String message){
        if (loginUser != null)
        {
            String userName = loginUser.getUsername();
            // 记录用户进入项目的日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, status, message));
        }
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:appmanager:query')")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }

}
